package cc.telecomdigital.tdstock;

import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import cc.mango.common.HttpUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_ClientParamMemory;
import cc.telecomdigital.tdstock.Tools.EncryptionAlg;

/**
 * get some system info on the handset
 * 
 * @author haibo
 * @desc modifby ouyangzhihui
 */
public class SystemInfo
{
	public static final String SUCCESS_CODE = "0";
	public static final String FAILED_CODE = "1";
	public static final String TAG = "SystemInfo";
	
	/**
	 * Get Wi-Fi Mac Addr Status
	 * 
	 * @param context
	 * @return String[] // 0:status=[(0)success,(1)failed], 1:deviceId, 2:message
	 */
	public static String[] GetDeviceIdAuthWifiMac(Context context)
	{
		String[] auth = new String[3];// 0:status, 1:deviceId, 2:message
		
		String tempDeviceId;
		tempDeviceId = DeviceIdSharedPrefTools.getDeviceId();
		
		TDStockLog.i(TAG, "prefDeviceId = " + tempDeviceId);
		
		if(tempDeviceId.trim().length() == DEVICE_ID_LENGTH)
		{
			auth[0] = SUCCESS_CODE;
			auth[1] = tempDeviceId;
			auth[2] = "";
			
			return auth;
		}
		
		try
		{
			// check wifi status
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			boolean isEnabled = wifiManager.isWifiEnabled();
			if (!isEnabled) // not Enabled
			{
				// turn on wifi
				wifiManager.setWifiEnabled(true);
			}
			
			String wifiMacAddress;
			
			long timesamp = System.currentTimeMillis();
			
			do {
				// read mac address
				WifiInfo wifiInfo = wifiManager.getConnectionInfo();
				wifiMacAddress = wifiInfo.getMacAddress();
				
				// 超時設置 默認4秒
				if((System.currentTimeMillis() - timesamp) >= 15000)
					break;
			} while (wifiMacAddress == null);
			
			if(wifiMacAddress == null)
			{
				auth[0] = FAILED_CODE;
				auth[1] = "";
				auth[2] = "未能檢查wifi狀態，請重啟wifi後，再試。";
			}
			else
			{
				String tmp = wifiMacAddress + getIMEI(context);
				String deviceId = UUID.nameUUIDFromBytes(tmp.getBytes()).toString();
				deviceId = deviceId.replace("-", "00");
				
				auth[0] = SUCCESS_CODE;
				auth[1] = deviceId;
				auth[2] = "";
				
				DeviceIdSharedPrefTools.saveDeviceId(deviceId);
			}
			wifiManager.setWifiEnabled(isEnabled);
		}
		catch(Exception e)
		{
			TDStockLog.i(TAG, "Wifi Status Exception = " + e.toString());
			// Error
			auth[0] = FAILED_CODE;
			auth[1] = "";
			auth[2] = "如果閣下正在使用wifi hot-spot，請先關閉，再試。";
		}
		return auth;
	}
	
	public static final int DEVICE_ID_LENGTH = 40;
	public static String  ACCOUNT_ID_FORMAT = "000000,00,000";
	public static Calendar	calendar	= Calendar.getInstance();
	public static final String EMPTY_WIFI_MAC_ADDRESS = "00:00:00:00:00:00";
	public static String current_wifi_mac_address = EMPTY_WIFI_MAC_ADDRESS;

	private static String keySet = "@@deviceinfotrace@@";

    public static String getDeviceExtraInfo(Context iContext)
    {
        String extraInfo;
        extraInfo = "XMF_" + android.os.Build.MANUFACTURER
                + "XBR_" + android.os.Build.BRAND
                + "XML_" + android.os.Build.MODEL
                + "XPD_" + android.os.Build.PRODUCT
                + "XID_" + android.os.Build.ID
                + "XDV_" + android.os.Build.DEVICE 
                + "XRL_" + android.os.Build.VERSION.RELEASE
                + "XSK_" + android.os.Build.VERSION.SDK
                + "XUT_" + String.valueOf(android.os.SystemClock.elapsedRealtime()).toString()
                + "XMC_" + getWifiMacAddress(iContext)
                + "XMI_"  + getIMEI(iContext);
        
        TDStockLog.e("Exam", "***** ExtraInfo = " + extraInfo);
        try
        {
            extraInfo = EncryptionAlg.encrypt(keySet, extraInfo);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        TDStockLog.e("Exam", "***** After ExtraInfo = " + extraInfo);
        return extraInfo;
    }
	
	public static String getDeviceId(Context context, String... mode)
	{
		String wifi_mac_address = getWifiMacAddress(context, mode);
		String tmp = wifi_mac_address + getIMEI(context);
		String deviceId = UUID.nameUUIDFromBytes(tmp.getBytes()).toString();
		current_wifi_mac_address = wifi_mac_address;
		deviceId = deviceId.replace("-", "00");
		
		TDStockLog.d(TAG, "deviceId = "+deviceId);
		return deviceId;
		
		/*String reg = "[^a-zA-Z0-9]";
		deviceId = deviceId.replaceAll(reg, "");   //modified by haibo, 2011-07-27, ----filter invalid char-----
		StringBuffer  buffer = new StringBuffer(deviceId);
		 int addTo =DEVICE_ID_LENGTH - deviceId.length();
		 if(addTo > 0) 
		 {
			 for(int item =0; item < addTo; item++) {
				 buffer.append("x");
			 }
		 }
		 else if(addTo < 0) 
		 {
			 buffer.delete(DEVICE_ID_LENGTH,  deviceId.length());
		 }
		TDStockLog.d(TAG, "deviceId = " +  buffer.toString().toLowerCase());
		return  buffer.toString().toLowerCase();*/
	}

	public static String getWifiMacAddress(Context context, String... mode)
	{
		final String EMPTY = EMPTY_WIFI_MAC_ADDRESS;
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String wifiMacAddress = wifiInfo.getMacAddress();
		wifiMacAddress = (wifiInfo == null) ? EMPTY : wifiMacAddress == null ? EMPTY : wifiMacAddress;
		TDStockLog.d(TAG, "mode lenght="+mode.length);
		// 非DelayMode下
		if(mode.length < 1 && wifiMacAddress.equals(EMPTY))
		{
			boolean isEnabled = wifiManager.isWifiEnabled(); // 記錄原來是否啟用
			TDStockLog.d(TAG, "isWifiEnabled=>"+isEnabled);
			
			/* 如果從未啟用過Wifi網絡，則啟用Wifi之後再關閉 */
			if (!wifiManager.isWifiEnabled())
			{
				wifiManager.setWifiEnabled(true);
			}
//			TDStockLog.d(TAG, "isWifiEnabled=>"+wifiManager.isWifiEnabled());
			long timesamp = System.currentTimeMillis();
			do {
				wifiInfo = wifiManager.getConnectionInfo();
				wifiMacAddress = wifiInfo.getMacAddress();
				wifiMacAddress = (wifiInfo == null) ? EMPTY : wifiMacAddress == null ? EMPTY : wifiMacAddress;
				
//				TDStockLog.d(TAG, "wifiMacAddress=>"+wifiMacAddress);
				
				// 超時設置 默認4秒
				if((System.currentTimeMillis() - timesamp) >= 15000)
					break;
				
			} while (wifiMacAddress.equals(EMPTY));
			
			TDStockLog.d(TAG, "usetime="+(System.currentTimeMillis() - timesamp));
			wifiManager.setWifiEnabled(isEnabled);
		}
		TDStockLog.d(TAG, "wifiMacAddress = " + wifiMacAddress);
		return wifiMacAddress;
	}

	public static String getIMEI(Context context)
	{
		final String nullReplaceMent = "000000000000000";
		final TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		String result = tm.getDeviceId();
		result = (result == null || result.length() < 1) ? nullReplaceMent
				: result;

		/*if (result.equals(nullReplaceMent))
		{
			result = String.format("%04d%02d", calendar.get(Calendar.YEAR),
					9 + calendar.get(Calendar.MONTH));
			if (result.length() < nullReplaceMent.length())
			{
				StringBuffer buff = new StringBuffer().append(result);
				while (buff.toString().length() < nullReplaceMent.length())
				{
					buff.append("0");
				}
				result = buff.toString();
			}
		}*/
		TDStockLog.d(TAG, "result = " + result);
		return result;
	}

	public static boolean isNetworkingConnected(Context context)
	{
		/*String mask = String.format("%04d%02d", calendar.get(Calendar.YEAR),
				9 + calendar.get(Calendar.MONTH));
		if (getDeviceId(context).contains(mask))
		{
			return true; // if the device is emulator, suppose it connected to the netwroking now. should remove this code before publish it to the market.
		}*/
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null)
		{
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null)
			{
				if (info.getState() == NetworkInfo.State.CONNECTED)
				{
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 登录，初始化程序设置
	 * @param context 
	 * @param mode 延迟模式“delay”,试用模式“activeCode”,帐号模式“accountLogin”
	 * @param user 帐号模式“accountLogin”的登入名
	 * @param pwd  帐号模式“accountLogin”的登入密码
	 * @param sessionAccount 
	 * @param sessionToken
	 */
	public static void initLoginApp(Context context, CommonDefn.ModeType mode,
			String user, String pwd, String sessionAccount, String sessionToken)
	{
		if (mode == CommonDefn.ModeType.DELARY || CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY.equals(user))
		{
			if(user == null)
			{
				user = CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY;
				pwd = CommonDefn.ACCOUNT_USER_PWD_TRIAL_DELAY;
			}
			((ITDLApplication) context).setDataMode(CommonDefn.DataMode.Delay);
			((ITDLApplication) context).setModeType(CommonDefn.ModeType.DELARY);
		}
		else if (mode == CommonDefn.ModeType.ACTIVECODE)
		{
			user = "";
			pwd = "";

			((ITDLApplication) context).setDataMode(CommonDefn.DataMode.Realtime);
			((ITDLApplication) context).setModeType(CommonDefn.ModeType.ACTIVECODE);

			((ITDLApplication) context).setAuthComeFromActivationCode(true);
		}
		else if (mode == CommonDefn.ModeType.ACCOUNTLOGIN)
		{
			((ITDLApplication) context).setDataMode(CommonDefn.DataMode.Realtime);
			((ITDLApplication) context).setModeType(CommonDefn.ModeType.ACCOUNTLOGIN);
		}

		((ITDLApplication) context).setUserName(user);
		((ITDLApplication) context).setPwd(pwd);
		
		String deviceId;
		deviceId = DeviceIdSharedPrefTools.getDeviceId();

		DBHelper dbHelper = new DBHelper(context);
		long userId = dbHelper.insertOrUpdateUser(user, pwd, deviceId);

		((ITDLApplication) context).setDeviceId(deviceId);
		((ITDLApplication) context).setUserId((int) userId);

		String rsi_term_setting = dbHelper.insertOrUpdatePreference(
				(int) userId, CommonDefn.DB_CHART_PREFER_RSITERM_CATALOGUE,
				"14", true);
		((ITDLApplication) context).setPreferRsiTerm(rsi_term_setting);
		dbHelper.cleanup();

	}
	
	public   static  String getFormattedAccountId(Context context) {
		  String result = ACCOUNT_ID_FORMAT;
		  String account = ((ITDLApplication) context).getSessionAccount();
		  if(account.endsWith("hk")) 
		  {
			  account = account.substring(0, account.length() -2);
		  }
		  try
		{
			  String[] elements = ACCOUNT_ID_FORMAT.split("[,\\.]");
			  StringBuffer buff = new StringBuffer();
			  int index = 0;
			  for(String str:  elements)
			  {
				  if(index + str.length()   <=  account.length())
				  {
					  buff.append( account.substring(index, index + str.length() ));
					  index += str.length();
					  buff.append("-");
				  }
			  }
			  buff.deleteCharAt(buff.toString().length()-1);
			  result = buff.toString();
		}
		catch (Exception e)
		{
			TDStockLog.e(TAG, e.getMessage() == null ? " unknow exception in getFormattedAccountId! "  : e.getMessage());
			e.printStackTrace();
		}
		TDStockLog.d(TAG, "account = "+result);
		  return  result;
	}
	
	public   static  String getFormattedAccountId(Context context, String account) {
		  String result = ACCOUNT_ID_FORMAT;
		  if(account.endsWith("hk")) 
		  {
			  account = account.substring(0, account.length() -2);
		  }
		  try
		{
			  String[] elements = ACCOUNT_ID_FORMAT.split("[,\\.]");
			  StringBuffer buff = new StringBuffer();
			  int index = 0;
			  for(String str:  elements)
			  {
				  if(index + str.length()   <=  account.length())
				  {
					  buff.append( account.substring(index, index + str.length() ));
					  index += str.length();
					  buff.append("-");
				  }
			  }
			  buff.deleteCharAt(buff.toString().length()-1);
			  result = buff.toString();
		}
		catch (Exception e)
		{
			TDStockLog.e(TAG, e.getMessage() == null ? " unknow exception in getFormattedAccountId! "  : e.getMessage());
			e.printStackTrace();
		}
		TDStockLog.d(TAG, "account = "+result);
		return  result;
	}
	
	//should call less times ;
	public static  String getServerTime(Context context, String format) {
		String result = "";
		ITDLApplication  app = null;
		try
		{
			String url = "";
			if(context != null) {
			/*	if(context instanceof  Activity) {
					 app = (ITDLApplication) context.getApplicationContext();
				}else {
					app =((ITDLApplication) context);
				}*/
				app =((ITDLApplication) context);
				String account = ((ITDLApplication) context).getSessionAccount();
				String token = ((ITDLApplication) context).getSessionToken();
				
				String addParam = new StringBuffer("account=").append(account)
						.append("&token=").append(token).toString();
				
				 url = "http://" + /*app.getWebServer()*/LS_ClientParamMemory.GetWebServerInfo() + "/iphone/getTime.do?" + addParam;
			}
			else {
				url = "http://quotedev2.telecomdigital.cc/iphone/getTime.do?bkdr=tslsit_9959";
			}
			
			
			String responseTxt = StringUtils.inputStreamToString(HttpUtils.urlToStream(url));
			Map<String,String> map = StringUtils.stringToMap(responseTxt, "Time");
			String dateTime = map.get("Time");
			if(format != null && format.trim().length() > 0) 
			{
				result = DateUtils.formatDate(DateUtils.strToDate(dateTime, "yyyyMMddHHmmss"), format);
			}
			else
			{
				result = dateTime;
			}
			
		}
		catch (Exception e)
		{
			TDStockLog.e(TAG, e.getMessage() == null ? " unknow exception in getServerTime! "  : e.getMessage());
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	static private String versionName = null;
	public static String getAppVersionName(Context iContext)
	{
		if (versionName != null)
			return versionName;
		
		PackageInfo packageInfo;
		try
		{
			packageInfo = iContext.getPackageManager().getPackageInfo(iContext.getPackageName(), 0);
			versionName = packageInfo.versionName;
		}
		catch (NameNotFoundException e)
		{
			 versionName =  "1.0.0";
		  /*  e.printStackTrace();
		    versionName = null;
		    //return a temporary version
		    return "NA";*/
		} 		
		
		return versionName;
	}
	
	
}
